#include "pm/cost.h"

using namespace pm;

const wxString Cost::TABLE_NAME   = wxT("costs");

Cost::Cost()
: db::Table()
, unit_cost(0.0)
, quantity(0.0)
, date(wxDateTime::Today())
{
}

Cost::Cost(wxSQLite3ResultSet& res)
: db::Table(res)
{
}

bool Cost::load(wxSQLite3ResultSet& res)
{
	return Table::load(res)
		&& unit_cost.load(res, wxT("unit_cost"), 0.0      )
		&& quantity.load( res, wxT("quantity"),  0.0      )
		&& name.load(     res, wxT("name")                )
		&& date.load(     res, wxT("date")                )
		&& id_task.load(  res, wxT("id_task"),   db::ID::undefined);
}

db::update_value_t Cost::prepare_insert(wxSQLite3Database& db)
{
	if (id_task.valid() == false) {
		return db::update_value_t(false, wxSQLite3Statement());
	}
	
	wxSQLite3Statement stmt = db.PrepareStatement("insert into costs values(null, ?, ?, ?, ?, ?)");
	stmt.Bind(1, unit_cost());
	stmt.Bind(2, quantity());
	stmt.Bind(3, name());
	stmt.BindDate(4, date());
	stmt.Bind(5, id_task());
	return db::update_value_t(true, stmt);
}

db::update_value_t Cost::prepare_update(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("update costs set unit_cost = ?, quantity = ?, name = ?, date = ?, id_task = ? where id = ?");
	stmt.Bind(1, unit_cost());
	stmt.Bind(2, quantity());
	stmt.Bind(3, name());
	stmt.BindDate(4, date());
	stmt.Bind(5, id_task());
	stmt.Bind(6, id());
	return db::update_value_t(true, stmt);
}


const wxString CostInfo::TABLE_NAME = wxT("view_costs");

CostInfo::CostInfo()
: Cost()
{
}

CostInfo::CostInfo(wxSQLite3ResultSet& res)
: Cost(res)
, id_project(res, wxT("id_project"), db::ID::undefined)
, task_name(res, wxT("task_name"))
{
}



GetCostsByProject::GetCostsByProject(const db::ID& id_project)
: id_project(id_project)
{
}

wxSQLite3Statement GetCostsByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, unit_cost, quantity, name, date, id_task, task_name, id_project from view_costs where id_project = ? order by date asc");
	stmt.Bind(1, id_project());
	return stmt;
}
